package com.example.ftptest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.commons.net.ftp.FTPFile;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class UploadActivity extends Activity {
	
	private static final String TAG = "UploadActivity";
	private  ListView maLV;
	private String  pass, host, user;
	private int port;
	private  MyFTPClient ftpClient;
	private  FTPFile[] ftpFiles;
	private File fichierLocal, dossierLocal;
	private FTPFile fichierServeur, dossierServeur;
	private Context monContext;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload);
		Button button1=(Button)findViewById(R.id.button1);
		monContext = this;
		//récupère les donnéees
		 Bundle extra= this.getIntent().getExtras();
	        
	        if(extra!=null){
	        	pass = extra.getString("pass");
	        	host = extra.getString("host");
	        	user = extra.getString("user");
	        	port = extra.getInt("port");
	        }
	        //se connecte au serveur FTP
	       ftpClient = new MyFTPClient();
	       Log.d(TAG, "HOST " +host);
	       Log.d(TAG, "USER " +user);
	       Log.d(TAG, "PASS " +pass);
	       Log.d(TAG, "PORT " +port);
	       ftpClient.ftpConnect(host, user, pass, port);
	       
	       uploadRefresh();
	       downloadRefresh();
	       
		button1.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub	
				
				downloadRefresh();
			}
			
		});
		
		Button button2=(Button)findViewById(R.id.button2);
		button2.setOnClickListener(new OnClickListener(){
		
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub	
			
				uploadRefresh();
			}
			
		});
		
		Button upload=(Button)findViewById(R.id.upload);
		upload.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try {
					Log.i(TAG, "upload");
					Log.i(TAG, "fichier : " + fichierLocal.getPath());
					Log.i(TAG, "dossier : " + dossierServeur.getName());
					ftpClient.ftpUpload(fichierLocal.getName(), fichierLocal.getName(),"/", monContext);
					//Refresh de la liste
					uploadRefresh();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		Button download=(Button)findViewById(R.id.download);
		download.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				try {
					Log.i(TAG, "download");
					Log.i(TAG, "fichier : " + fichierServeur.getName());
					//Log.i(TAG, "dossier : " + dossierLocal.getName());
					ftpClient.ftpDownload(fichierServeur.getName(), Environment.getExternalStorageDirectory().getName() + "/" + fichierServeur.getName());
					//Refresh de la liste
					downloadRefresh();
					
				} catch (Exception e) {
					e.printStackTrace();
				}				
			}
		});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.upload, menu);
		return true;
	}
	private File[] localFiles;
	public void localPrintFilesList(File dir, String header)
	{
	    try {
	    	Log.d(TAG, "recuperation des données du repertoires");
	    	maLV = (ListView) findViewById(R.id.listView1);
	    	localFiles = dir.listFiles();
	        int length = localFiles.length;
	        
	        //Création de la ArrayList qui nous permettra d'alimenter la listView
	         ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
	  
	         //On déclare la HashMap qui contiendra les informations pour un item
	         HashMap<String, String> map;
	         
	        //String[] values = new String[length];
	        Log.d(TAG, "nombre de fichier dans le repertoire : " +length);
	        for (int i = 0; i < length; i++) {
	        	// initialisation du HashMap
	        	map = new HashMap<String, String>();
	          
	            String name = localFiles[i].getName();
	            boolean isFile = localFiles[i].isFile();
	            //values[i] = name;
	            if (isFile) {
	                Log.i(TAG, "File : " + name);
	                map.put("img", String.valueOf(R.drawable.fichier));
	            }
	            else {
	                Log.i(TAG, "Directory : " + name);
	                map.put("img", String.valueOf(R.drawable.dossier));
	            }
	            map.put("title", name);        
		        
		        //Ajoute à la liste    
		        listItem.add(map);
	        }

			//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				//R.layout.listviewitem, android.R.id.text1, values);
			SimpleAdapter mSchedule = new SimpleAdapter (this.getBaseContext(), listItem, R.layout.listviewitem,
		               new String[] {"img", "title"}, new int[] {R.id.img, R.id.title});
			//TextView tv = new TextView(this);
			//tv.setText(header);
			//maLV.addHeaderView(tv);
			maLV.setAdapter(mSchedule);
			
		
			maLV.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					  Log.i(TAG, "Position : " + position);
					  Log.i(TAG, "longueur liste : " + localFiles.length);
					//On regarde si c'est un fichier ou un dossier
					boolean isFile = localFiles[position].isFile();
					if (isFile)
					{
						fichierLocal =  localFiles[position];
					}
					else
					{
						dossierLocal = localFiles[position];
						localPrintFilesList(localFiles[position], localFiles[position].getName());
					}
					
				}
			});
	    } catch(Exception e) {
	        e.printStackTrace();
	    }
	} 
	
	
	public void serverPrintFilesList(String ftpDir, String header)
	{
	    try {
	    	maLV = (ListView) findViewById(R.id.ListView2);
	    	Log.d(TAG, "recuperation des données du repertoires");
	        ftpFiles = ftpClient.mFTPClient.listFiles(ftpDir);
	        for (FTPFile ftpliste : ftpFiles){
	        Log.d(TAG, "liste des repertoire : " +ftpliste.getName() );
	        }
	        int length = ftpFiles.length;
	        Log.d(TAG, "nombre de fichier dans le repertoire : " +length);
	        //Création de la ArrayList qui nous permettra d'alimenter la listView
	         ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
	  
	         //On déclare la HashMap qui contiendra les informations pour un item
	         HashMap<String, String> map;
	         
	        for (int i = 0; i < length; i++) {
	          	map = new HashMap<String, String>();
		          
	            String name = ftpFiles[i].getName();
	            boolean isFile = ftpFiles[i].isFile();

	            if (isFile) {
	                Log.i(TAG, "File : " + name);
	                map.put("img", String.valueOf(R.drawable.fichier));
	            }
	            else {
	                Log.i(TAG, "Directory : " + name);
	                map.put("img", String.valueOf(R.drawable.dossier));
	            }
	            map.put("title", name);        
		        
		        //Ajoute à la liste    
		        listItem.add(map);
	        }
	        
	      //ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
			//R.layout.listviewitem, android.R.id.text1, values);
		SimpleAdapter mSchedule = new SimpleAdapter (this.getBaseContext(), listItem, R.layout.listviewitem,
	               new String[] {"img", "title"}, new int[] {R.id.img, R.id.title});
		//TextView tv = new TextView(this);
		//tv.setText(header);
		//maLV.addHeaderView(tv);
		maLV.setAdapter(mSchedule);
		
	
		maLV.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//On récupère le titre de l'Item dans un String
				boolean isFile = ftpFiles[position].isFile();
				if (isFile)
				{
					fichierServeur = ftpFiles[position];
				}
				else
				{
					dossierServeur = ftpFiles[position];
					serverPrintFilesList(ftpFiles[position].getName(), ftpFiles[position].getName());
				}
				
			}
		});
	    } catch(Exception e) {
	        e.printStackTrace();
	    }
	} 
	
	public void downloadRefresh(){
		//Rafrechit la liste
		Log.d(TAG, "avant recuperation du repertoire");
		File dir= Environment.getExternalStorageDirectory();
		Log.d(TAG, "apres recuperation du repertoire");
		Log.d(TAG, dir.toString());
		localPrintFilesList(dir, "LOCAL FILES");
		
	}
	
	public void uploadRefresh(){
		//Rafrechit la liste
		Log.d(TAG, "Liste du repertoire du server1 : " +ftpClient.ftpGetCurrentWorkingDirectory());
		try {
			serverPrintFilesList(ftpClient.ftpGetCurrentWorkingDirectory(), "SERVER FILES");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.d(TAG, "Impossible de recuperer la liste  ");
			e.printStackTrace();
		}
		
	}

}
